package com.alpha.gateway.utils;

import cn.hutool.core.date.DateUnit;
import com.alpha.core.utils.CollectionUtil;
import com.google.common.collect.ImmutableMap;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Token 工具类
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@Slf4j
public class TokenUtil {
    /**
     * Authorization认证开头是"bearer "
     */
    private static final String BEARER = "Bearer ";

    public static final Long EXPIRES = 2 * DateUnit.HOUR.getMillis();

    public static final String SIGNING_KEY = "&&J(K*L(S*D#F%U@)(*&*(#@$I()";

    public static String createToken(Map<String, String> claims) {
        Date now = new Date();
        return Jwts.builder()
                // 自定义数据
                .setClaims(new HashMap<>(claims))
                // 签发时间
                .setIssuedAt(now)
                // 过期时间
                .setExpiration(new Date(now.getTime() + EXPIRES))
                // 签发者
                .setIssuer(null)
                // 面向用户
                .setSubject(null)
                .signWith(SignatureAlgorithm.HS512, SIGNING_KEY)
                .compact();
    }

    public static Map<String, Object> parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SIGNING_KEY)
                    .parseClaimsJws(token.substring(BEARER.length()))
                    .getBody();
        } catch (Exception e) {
            return CollectionUtil.emptyMap();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        String token = createToken(ImmutableMap.<String, String>builder()
                .put("userid", "101")
                .put("username", "alpha")
                .build());

        log.info(parseToken(token).toString());

        Thread.sleep(5000);

        log.info(parseToken(token).toString());
    }
}
